// pages/login/login.js
import { toast } from '../../utils/extendAPI'
import { reqLogin, getUserInfo } from '../api/login'
import { setStorage } from '../../utils/storage'
import { ComponentWithStore } from 'mobx-miniprogram-bindings'
import { userStore } from '../../stores/index'
import { debounce } from 'miniprogram-licia'
ComponentWithStore({
    storeBindings: {
        store: userStore,
        fields: ['token', 'userInfo'],
        actions: ['setToken', 'gsetUerInfo']
    },
    methods: {
        // 登录
        login: debounce(function () {
            wx.login({
                success: async ({ code }) => {
                    if (code) {
                        const { data } = await reqLogin()
                        setStorage('token', data.token)
                        this.setToken('data.token')
                        this.getUserInfo()
                        wx.navigateBack()
                    } else {
                        toast({
                            title: '授权失败请重新登录！'
                        })
                    }
                }
            })
        }, 500),
        //获取用户信息
        async getUserInfo() {
            const { data } = await getUserInfo()
            this.getUserInfo(data)
            setStorage('userInfo', data)
        }
    }
})
